<template>
  <d2-container>
    <div style="margin: 20px">
      <el-form label-width="100px" label-position="left" size="large" :model="form" :rules="rules" ref="trainForm">
        <el-card>
          <div slot="header" class="clearfix">
            <div>
              <span style="text-align: left; font-size: 28px; color: #1E90FF"><b>| </b></span>
              <span style="text-align: left; font-size: 22px"><b>模型信息</b></span>
            </div>
          </div>
          <div style="width: 45%">
            <el-form-item label="选择项目" prop="project">
              <el-select style="width: 100%" clearable v-model="form.project" placeholder="请选择"
                         :disabled="isDisabled" @change="selectChange">
                <el-option v-for="item in projects" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="模型名称" prop="name">
              <el-input style="width: 100%" v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
          </div>
        </el-card>
        <el-card style="margin-top: 20px">
          <div slot="header" class="clearfix">
            <div>
              <span style="text-align: left; font-size: 28px; color: #1E90FF"><b>| </b></span>
              <span style="text-align: left; font-size: 22px"><b>添加数据</b></span>
            </div>
          </div>
          <div style="width: 80%">
            <el-table :data="datasets" border stripe ref="trainTable" @selection-change="handleSelectionChange"
                      @select-all="trainDialogCheck" @select="trainDialogCheck">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="id" label="ID" width="80"></el-table-column>
              <el-table-column prop="title" label="数据集"></el-table-column>
              <el-table-column prop="version" label="版本" width="100"></el-table-column>
              <el-table-column prop="task_number" label="图片数量" width="100"></el-table-column>
            </el-table>
            <el-form-item label="自定义测试集" style="margin-top: 10px">
              <el-switch v-model="form.test"></el-switch>
            </el-form-item>
            <el-table v-if="form.test===true" :data="datasets" border stripe ref="testTable"
                      @selection-change="handleSelectionChange"
                      @select-all="testDialogCheck" @select="testDialogCheck">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="id" label="ID" width="80"></el-table-column>
              <el-table-column prop="title" label="数据集"></el-table-column>
              <el-table-column prop="version" label="版本" width="100"></el-table-column>
              <el-table-column prop="task_number" label="图片数量" width="100"></el-table-column>
            </el-table>
          </div>
        </el-card>
        <el-card style="margin-top: 20px">
          <div slot="header" class="clearfix">
            <div>
              <span style="text-align: left; font-size: 28px; color: #1E90FF"><b>| </b></span>
              <span style="text-align: left; font-size: 22px"><b>训练配置</b></span>
            </div>
          </div>
          <div style="width: 80%;margin-top: 30px">
            <el-form-item label="训练轮数：" :rules="[{ required: true, trigger: 'change' }]">
              <el-slider :min="1" :max="500" v-model="form.epochs" show-input style="margin-left: 6px"></el-slider>
            </el-form-item>
            <el-form-item label="批次大小：" :rules="[{ required: true, trigger: 'change' }]">
              <el-slider :min="16" :max="512" v-model="form.batchsize" :marks="marks" @change="onSliderChange"
                         show-input style="margin-left: 6px"></el-slider>
            </el-form-item>
            <el-form-item label="模型版本：" style="margin-top:30px" :rules="[{ required: true, trigger: 'change' }]">
              <el-radio-group v-model="form.model_version">
                <el-radio-button label="s">轻量级模型</el-radio-button>
                <el-radio-button label="m">中等模型</el-radio-button>
                <el-radio-button label="l">大型模型</el-radio-button>
                <el-radio-button label="x">超大型模型</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </div>
        </el-card>

        <div style="float:right; margin-top: 10px;padding-bottom: 10px">
          <el-button type="primary" size="medium" autocomplete="off" @click="submit">开始训练
          </el-button>
        </div>
      </el-form>
    </div>
  </d2-container>
</template>

<script>

import {AddObj, GetList, GetProObj, GetDatasets} from './api.js'
import {v4 as uuidv4} from 'uuid'
import {Loading} from 'element-ui'

export default {
  name: 'index',
  data() {
    return {
      projects: [],
      isDisabled: false,
      form: {
        test: false,
        model_version: 's'
      },
      rules: {
        project: [
          {required: true, message: '请选择项目', trigger: 'change'}
        ],
        name: [
          {required: true, message: '请输入模型名称', trigger: 'blur'},
          {
            pattern: /^[a-zA-Z0-9][a-zA-Z0-9_-]{2,19}$/,
            message: '名称应以字母或数字开头, 只含字母、数字、_和-, 长度为3-20个字符',
            trigger: 'blur'
          }
        ]
      },
      dialogFormVisible: false,
      datasets: [], // 数据集
      selectRadio: 0, // 默认选中第一行数据
    }
  },
  rules: {
    model: []
  },
  computed: {
    marks() {
      const marks = {}
      for (let i = 16; i <= 512; i *= 2) {
        marks[i] = i.toString()
      }
      return marks
    }
  },
  methods: {
    onSliderChange(value) {
      if (!(value in this.marks)) {
        const keys = Object.keys(this.marks)
        const index = keys.findIndex(key => key > value)
        if (index === 0) {
          this.form.batchsize = Number(keys[0])
        } else if (index === -1) {
          this.form.batchsize = Number(keys[keys.length - 1])
        } else {
          const prev = Number(keys[index - 1])
          const next = Number(keys[index])
          this.form.batchsize = Math.abs(value - prev) < Math.abs(value - next) ? prev : next
        }
      }
    },
    // 获取所有项目
    getProjects() {
      const query = {creator_id: this.$store.state.d2admin.user.info.user_id}
      GetList(query).then(response => {
        this.projects = response.data.data
      })
    },
    // 根据项目获取对应数据集
    selectChange(item) {
      this.form.project = item
      this.getDatasets()
    },
    // 获取项目对应类型的数据集
    getDatasets() {
      GetProObj(this.form.project).then(response => {
        GetDatasets().then(res => {
          const data = []
          for (let i = 0; i < res.results.length; i++) {
            if (res.results[i].type === response.data.type &&
              res.results[i].task_number !== 0 && // 数据集非空
              res.results[i].task_number === res.results[i].finished_task_number && // 数据集标注完成
              res.results[i].status === true) { // 数据集已上传
              data.push(res.results[i])
            }
          }
          this.datasets = data
        })
      })
    },
    // 表格复选框只能单选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    trainDialogCheck: function (selection, row) {
      // console.log(selection, row);
      // 清除所有勾选项
      this.$refs.trainTable.clearSelection()
      this.form.dataset_id = undefined
      // 当表格数据都没有被勾选的时候 就返回
      // 主要用于将当前勾选的表格状态清除
      if (selection.length === 0) {
        return
      }
      if (row) {
        this.selectioned = row
        this.$refs.trainTable.toggleRowSelection(row, true)
        this.form.dataset_id = row.id
      }
    },
    testDialogCheck: function (selection, row) {
      // console.log(selection, row);
      // 清除所有勾选项
      this.$refs.testTable.clearSelection()
      this.form.test_dataset_id = undefined
      // 当表格数据都没有被勾选的时候 就返回
      // 主要用于将当前勾选的表格状态清除
      if (selection.length === 0) {
        return
      }
      if (row) {
        this.selectioned = row
        this.$refs.testTable.toggleRowSelection(row, true)
        this.form.test_dataset_id = row.id
      }
    },
    // 提交训练
    async submit() {
      this.$refs.trainForm.validate(async (valid) => {
        if (valid) {
          if (typeof (this.form.dataset_id) === 'undefined') {
            this.$message.error('请选择数据集')
            return
          }
          if (typeof (this.form.test_dataset_id) === 'undefined' && this.form.test === true) {
            this.$message.error('请选择测试数据集')
            return
          }
          console.log(this.form)
          // 启动loading服务
          const loadingInstance = Loading.service({
            target: document.getElementById('detailClass'),
            fullscreen: true,
            text: '已提交训练，请稍候...',
            background: 'rgba(225,225,225,0.8)'
          })
          // this.form.name = this.form.name + uuidv4()
          await AddObj(this.form).then(response => {
          }).catch(error => {
            this.$message.error('训练失败')
            console.log(error)
          })
          // 关闭loading
          loadingInstance.close()
          await this.$router.push('/model/my')
        } else {
          return false
        }
      })
    }
  },
  created: function () {
    // 获取传递的项目ID
    const projectID = this.$route.query.id
    // 已选择项目
    if (typeof (projectID) !== 'undefined') {
      this.form.project = projectID * 1
      this.isDisabled = true
      this.getDatasets()
    }
    this.getProjects()
  }
}
</script>

<style scoped>
</style>
